package com.hpit.shiro.realms;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;

/**
 * Created by Administrator on 2017/3/9.
 */
public class MyRealm1 implements Realm{

    @Override  //给Realm取个名
    public String getName() {
        return "MyRealm1";
    }

    @Override  //看传入的哪个类型的Token，是否符合指定的Token类型，符合则返回true，否则，返回false
    public boolean supports(AuthenticationToken authenticationToken) {
        return authenticationToken instanceof UsernamePasswordToken;  //若传入的Token符合指定的Token则返回true
    }

    @Override
    public AuthenticationInfo getAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("使用自定义realm");
        //实现自定义的Realm验证逻辑
        //1、得到身份和凭证
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[])authenticationToken.getCredentials()) ;  //密码强转成字符数组，后转为String
        //2、实现验证逻辑
        if (!username.trim().equals("admin")){
            throw new UnknownAccountException("未知的身份");
        }
        if (!password.trim().equals("123321")){
            throw new UnknownAccountException("错误的凭证");
        }
        if (username.trim().equals("admin")&&password.trim().equals("123321")){
            return new SimpleAuthenticationInfo(username,password,this.getName());
        }
        return null;
    }
}
